import {
  storage
} from '@/utils/cache'
import Vue from 'vue'

const types = {
  isLogin: 'isLogin', // 是否登入
  userInfo: 'userInfo', // 用户信息
  code: 'code', // uni.login().code
  token: 'token',
  gameInfo: 'gameInfo', //游戏信息
  shareUserId: 'shareUserId', // 邀请人ID
}

const state = {
  [types.isLogin]: storage.get(types.isLogin, false),
  [types.userInfo]: {},
  [types.code]: storage.get(types.code, ''),
  [types.token]: storage.get(types.token, ''),
  [types.gameInfo]: storage.get(types.gameInfo, ''),
  [types.shareUserId]: null,
}

const getters = {
  _isLogin(state) {
    return state[types.isLogin]
  },
  _userInfo(state) {
    console.log(state[types.userInfo])
    return state[types.userInfo]
  },
  _code(state) {
    return state[types.code]
  },
  _token(state) {
    return state[types.token]
  },
  _gameInfo(state) {
    return state[types.gameInfo]
  },
  _shareUserId(state) {
    return state[types.shareUserId]
  },
}

const actions = {
  [types.isLogin + 'Up']: async ({
    commit
  }, state) => {
    return commit(types.isLogin, storage.set(types.isLogin, state))
  },
  [types.userInfo + 'Up']: async ({
    commit
  }, state) => {
    return commit(types.userInfo, state)
  },
  [types.code + 'Up']: async ({
    commit
  }, state) => {
    return commit(types.code, storage.set(types.code, state))
  },
  [types.token + 'Up']: async ({
    commit
  }, state) => {
    return commit(types.token, storage.set(types.token, state))
  },
  [types.gameInfo + 'Up']: async ({
    commit
  }, state) => {
    const gameInfo = await Vue.prototype.$api.login.getUserInfo();
    return commit(types.gameInfo, gameInfo)
  },
  [types.shareUserId + 'Up']: async ({
    commit,
    state,
    dispatch
  }, shareUserId = null) => {
    return commit(types.shareUserId, shareUserId)
  },
}

const mutations = {
  [types.isLogin]: (state, res) => {
    state[types.isLogin] = res
  },
  [types.userInfo]: (state, res) => {
    state[types.userInfo] = res
  },
  [types.code]: (state, res) => {
    state[types.code] = res
  },
  [types.token]: (state, res) => {
    state[types.token] = res
  },
  [types.gameInfo]: (state, res) => {
    state[types.gameInfo] = res
  },
  [types.shareUserId]: (state, res) => {
    state[types.shareUserId] = res
  },
}

export default {
  namespaced: true,
  types,
  state,
  getters,
  actions,
  mutations
}
